package com.fang.transfer.file.udp;


import com.fang.transfer.file.ThreadContext;
import com.fang.transfer.file.common.RequestListener;
import com.fang.transfer.file.listener.RequestListenerManagement;
import com.fang.transfer.file.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

@Service
@Slf4j
public class ServiceUDP {

    @Autowired
    private RequestListenerManagement requestListenerManagement;

    public ServiceUDP() throws Exception {
        // 1.创建服务器端DatagramSocket，指定端口
        DatagramSocket socket = new DatagramSocket(8889);

        new Thread() {
            @Override
            public void run() {
                while (true) {
                    byte[] data = new byte[1024];
                    try {
                        DatagramPacket packet = new DatagramPacket(data, data.length);
                        socket.receive(packet);
                        log.info("UPD信息收集 来源IP:{} port:{}", packet.getAddress(), packet.getPort());
                        String info = new String(data, 0, packet.getLength());
                        String code = info.substring(0, 3);
                        String json = info.substring(3);
                        RequestListener listener = requestListenerManagement.getByCode(code);
                        Object param = listener.jsonToParam(json);
                        try {
                            ThreadContext.setUdpPacketThreadLocal(packet);
                            listener.handle(param);
                        } catch (Exception ex) {
                            throw ex;
                        } finally {
                            ThreadContext.removeUdpPacketThreadLocal();
                        }
                    } catch (Exception e) {
                        log.error("error", e);
                    }
                }
            }
        }.start();

    }

}
